<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>量子增强智能导学系统Q-ITS</title>
    <style>
        :root {
            --primary-color: #007bff; --primary-hover: #0056b3; --secondary-color: #007bff; --secondary-hover: #0069d9;
            --tertiary-color: #6c757d; --tertiary-hover: #5a6268; --strengthen-color: #28a745; --strengthen-hover: #218838;
            --light-gray: #f8f9fa; --dark-gray: #343a40; --border-color: #dee2e6;
            --correct-bg: #e9f7ef; --correct-border: #28a745; --correct-text: #155724;
            --incorrect-bg: #f8d7da; --incorrect-border: #dc3545; --incorrect-text: #721c24;
            --bg-color: #f0f2f5;
        }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background-color: var(--bg-color); color: var(--dark-gray); margin: 0; padding: 20px; display: flex; justify-content: center; align-items: flex-start; min-height: 100vh; }
        .container { width: 100%; max-width: 800px; background-color: white; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); overflow: hidden; }
        h1 { text-align: center; color: var(--dark-gray); padding: 20px 25px; margin: 0; border-bottom: 1px solid var(--border-color); background-color: #fafafa; }
        h2 { text-align: left; color: #1a2c4e; padding: 20px 25px; margin: 0; border-bottom: 1px solid var(--border-color); background-color: #fafafa; font-size: 1.5rem; }
        .content-padding { padding: 25px; }
        #topic-form { display: flex; gap: 10px; }
        #topic-input { flex-grow: 1; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px; }
        .btn { padding: 12px 25px; font-size: 1rem; font-weight: 500; border: none; border-radius: 8px; cursor: pointer; transition: all 0.3s ease; text-decoration: none; display: inline-block; color: white; }
        .btn-strengthen { background-color: var(--strengthen-color); }
        .btn-strengthen:hover { background-color: var(--strengthen-hover); transform: translateY(-2px); }
        .btn-secondary { background-color: var(--secondary-color); }
        .btn-secondary:hover { background-color: var(--secondary-hover); transform: translateY(-2px); }
        .btn-tertiary { background-color: var(--tertiary-color); }
        .btn-tertiary:hover { background-color: var(--tertiary-hover); transform: translateY(-2px); }
        #question-text { font-size: 1.25rem; margin-bottom: 20px; line-height: 1.5; }
        #options-container { display: flex; flex-direction: column; gap: 10px; }
        .option-btn { width: 100%; padding: 15px; text-align: left; background-color: var(--light-gray); border: 1px solid var(--border-color); border-radius: 8px; font-size: 1rem; cursor: pointer; transition: all 0.2s ease; }
        .option-btn:not(:disabled):hover { background-color: #e2e6ea; }
        .option-btn:disabled { cursor: not-allowed; background-color: #e9ecef; }
        #post-answer-controls { display: flex; justify-content: center; gap: 20px; margin-top: 30px; }
        .loader { display: none; margin: 40px auto; border: 5px solid var(--light-gray); border-top: 5px solid var(--primary-color); border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        .hidden { display: none !important; }

        /* --- 新的报告样式 --- */
        #quantum-analysis-container { text-align: center; }
        .mastery-card { background: linear-gradient(135deg, #4a69bd, #1e377a); color: white; padding: 30px 20px; border-radius: 10px; margin-bottom: 25px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); }
        .mastery-level { font-size: 2rem; font-weight: bold; margin: 0 0 10px 0; letter-spacing: 2px; }
        .mastery-comment { font-size: 1.1rem; margin: 0 0 15px 0; opacity: 0.9; }
        .mastery-suggestion { font-size: 0.95rem; font-style: italic; opacity: 0.8; }
        #summary-actions { display: flex; justify-content: center; gap: 15px; flex-wrap: wrap; }

        /* --- MODIFIED: 答题详情手风琴样式 --- */
        #summary-content { padding: 0; margin: 0; }
        .detail-item { border-radius: 8px; margin-bottom: 10px; overflow: hidden; border: 1px solid var(--border-color); }
        .detail-header { display: flex; justify-content: space-between; align-items: center; padding: 15px; cursor: pointer; transition: background-color 0.3s; user-select: none; }
        .detail-header:hover { background-color: #f0f2f5; }
        .detail-header span { font-weight: 500; }
        .detail-header .status { padding: 4px 10px; border-radius: 12px; font-size: 0.9rem; color: white; }
        .detail-item.correct .detail-header { background-color: var(--correct-bg); }
        .detail-item.correct .status { background-color: var(--correct-border); }
        .detail-item.incorrect .detail-header { background-color: var(--incorrect-bg); }
        .detail-item.incorrect .status { background-color: var(--incorrect-border); }
        .detail-content { padding: 20px; border-top: 1px solid var(--border-color); display: none; /* 默认隐藏 */ }
        .detail-content.active { display: block; /* 点击后显示 */ }
        .detail-content p { margin: 0 0 12px 0; line-height: 1.6; }
        .detail-content p strong { color: var(--dark-gray); min-width: 80px; display: inline-block; }
        .detail-content .explanation { margin-top: 15px; padding-top: 15px; border-top: 1px dashed #ccc; font-style: italic; color: #555; }
        .user-answer.incorrect { color: var(--incorrect-border); font-weight: bold; }
        .user-answer.correct { color: var(--correct-border); font-weight: bold; }

        @media (max-width: 600px) {
            body { padding: 10px; }
            .container { padding: 0; }
            .content-padding { padding: 15px; }
            h1, h2 { font-size: 1.3rem; padding: 15px; }
            #summary-actions { flex-direction: column; align-items: stretch; }
            .btn { width: 100%; box-sizing: border-box; }
        }
    </style>
</head>
<body>

    <div class="container">
        <!-- 初始页面和答题页面容器 -->
        <div id="main-content">
            <h1>量子增强智能导学系统Q-ITS</h1>
            <div id="topic-form-container" class="content-padding">
                <form id="topic-form"><input type="text" id="topic-input" placeholder="请输入一个知识主题开始测试" required><button type="submit" class="btn btn-secondary">开始测试</button></form>
            </div>
            <div id="loader" class="loader"></div>
            <div id="question-container" class="hidden content-padding">
                <p id="question-text"></p>
                <div id="options-container"></div>
            </div>
            <div id="post-answer-controls" class="hidden content-padding">
                <button id="next-question-btn" class="btn btn-secondary">下一题</button>
                <button id="end-session-btn" class="btn btn-tertiary">结束答题</button>
            </div>
        </div>

        <!-- 结果报告页面容器 -->
        <div id="summary-container" class="hidden">
            <div id="quantum-analysis-container">
                <h2>量子评估报告</h2>
                <div class="content-padding">
                    <div id="quantum-loader" class="loader" style="display: block;"></div>
                    <div id="quantum-result" class="hidden mastery-card">
                        <div class="mastery-level"></div>
                        <p class="mastery-comment"></p>
                        <p class="mastery-suggestion"></p>
                    </div>
                </div>
            </div>
            <div id="summary-actions" class="content-padding" style="padding-top: 0;">
                <button id="strengthen-btn" class="btn btn-strengthen">继续强化</button>
                <button id="new-learning-btn" class="btn btn-secondary">新的学习</button>
                <button id="cancel-learning-btn" class="btn btn-tertiary">取消学习</button>
            </div>
            <div id="details-container">
                <h2 id="summary-title">答题情况一览</h2>
                <!-- MODIFIED: 这里现在是一个 div，而不是 ul -->
                <div id="summary-content" class="content-padding"></div>
            </div>
        </div>
    </div>

    <script>
        // --- DOM 元素获取 (无变化) ---
        const mainContentContainer = document.getElementById('main-content');
        const topicFormContainer = document.getElementById('topic-form-container');
        const topicForm = document.getElementById('topic-form');
        const topicInput = document.getElementById('topic-input');
        const loader = document.getElementById('loader');
        const questionContainer = document.getElementById('question-container');
        const questionText = document.getElementById('question-text');
        const optionsContainer = document.getElementById('options-container');
        const postAnswerControls = document.getElementById('post-answer-controls');
        const nextQuestionBtn = document.getElementById('next-question-btn');
        const endSessionBtn = document.getElementById('end-session-btn');
        const summaryContainer = document.getElementById('summary-container');
        const summaryContent = document.getElementById('summary-content');
        const summaryTitle = document.getElementById('summary-title');
        const quantumContainer = document.getElementById('quantum-analysis-container');
        const quantumLoader = document.getElementById('quantum-loader');
        const quantumResultDiv = document.getElementById('quantum-result');
        const strengthenBtn = document.getElementById('strengthen-btn');
        const newLearningBtn = document.getElementById('new-learning-btn');
        const cancelLearningBtn = document.getElementById('cancel-learning-btn');

        let currentTopic = '';

        // --- 核心功能函数 ---

        // <<< CRITICAL CHANGE: displaySummary 函数被完全重写 >>>
        function displaySummary(data) {
            summaryTitle.textContent = `“${currentTopic}” 答题情况一览`;
            summaryContent.innerHTML = ''; // 清空容器

            if (data.length === 0) {
                summaryContent.innerHTML = '<p style="text-align:center;">没有本次测试的答题记录。</p>';
                return;
            }

            data.forEach(item => {
                const resultClass = item.is_correct ? 'correct' : 'incorrect';
                const statusText = item.is_correct ? '回答正确' : '回答错误';

                // 获取选项文本
                const userAnswerText = item.options[item.user_answer] || '未作答';
                const correctAnswerText = item.options[item.correct_answer];

                // 创建手风琴结构的 HTML
                const itemDiv = document.createElement('div');
                itemDiv.className = `detail-item ${resultClass}`;

                itemDiv.innerHTML = `
                    <div class="detail-header">
                        <span>题目 ${item.question_num}</span>
                        <span class="status">${statusText}</span>
                    </div>
                    <div class="detail-content">
                        <p><strong>题干:</strong> ${item.question_text}</p>
                        <p><strong>难度:</strong> ${item.difficulty}</p>
                        <p><strong>用时:</strong> ${item.time_taken} 秒</p>
                        <p><strong>你的答案:</strong> <span class="user-answer ${resultClass}">${item.user_answer}. ${userAnswerText}</span></p>
                        <p><strong>正确答案:</strong> ${item.correct_answer}. ${correctAnswerText}</p>
                        <p class="explanation"><strong>解析:</strong> ${item.explanation}</p>
                    </div>
                `;

                summaryContent.appendChild(itemDiv);

                // 为每个头部添加点击事件，用于展开/折叠内容
                const header = itemDiv.querySelector('.detail-header');
                const content = itemDiv.querySelector('.detail-content');
                header.addEventListener('click', () => {
                    content.classList.toggle('active');
                });
            });

            summaryContainer.classList.remove('hidden');
        }

        // --- 其他所有 JavaScript 函数 (getNextQuestion, submitAnswer, 等) 保持不变 ---
        // --- 它们将在这里... ---
        async function getNextQuestion(topic, isStrengthening = false) {
            setLoadingState(true);
            try {
                const response = await fetch('/generate-question', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ topic: topic, is_strengthening: isStrengthening })
                });
                if (!response.ok) {
                    const errData = await response.json();
                    throw new Error(errData.error || `获取题目失败: ${response.statusText}`);
                }
                const data = await response.json();
                if (data.error) throw new Error(data.error);
                currentTopic = topic;
                displayQuestion(data);
            } catch (error) {
                alert(error.message);
                showInitialState();
            } finally {
                setLoadingState(false);
            }
        }

        function displayQuestion(data) {
            questionText.textContent = data.question_text;
            optionsContainer.innerHTML = '';
            for (const [key, value] of Object.entries(data.options)) {
                const button = document.createElement('button');
                button.className = 'option-btn';
                button.dataset.key = key;
                button.textContent = `${key}. ${value}`;
                button.onclick = () => submitAnswer(key);
                optionsContainer.appendChild(button);
            }
            questionContainer.classList.remove('hidden');
        }

        async function submitAnswer(selectedKey) {
            document.querySelectorAll('.option-btn').forEach(btn => btn.disabled = true);
            await fetch('/submit-answer', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ answer: selectedKey })
            });
            questionContainer.classList.add('hidden');
            postAnswerControls.classList.remove('hidden');
        }

        async function endSession() {
            setLoadingState(true, postAnswerControls);
            try {
                const response = await fetch('/end-session', { method: 'POST' });
                if (!response.ok) throw new Error('获取答题报告失败');
                const summaryData = await response.json();
                if (summaryData.error) throw new Error(summaryData.error);
                setLoadingState(false);
                mainContentContainer.classList.add('hidden');
                displaySummary(summaryData);
                fetchAndDisplayQuantumAnalysis(summaryData);
            } catch (error) {
                alert(error.message);
                showInitialState();
            }
        }

        async function fetchAndDisplayQuantumAnalysis(summaryData) {
            quantumLoader.style.display = 'block';
            quantumResultDiv.classList.add('hidden');
            try {
                const response = await fetch('/get-quantum-analysis', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(summaryData)
                });
                if (!response.ok) throw new Error('获取量子评估失败');
                const result = await response.json();
                if (result.error) throw new Error(result.error);
                quantumResultDiv.querySelector('.mastery-level').textContent = result.feedback.level;
                quantumResultDiv.querySelector('.mastery-comment').textContent = result.feedback.comment;
                quantumResultDiv.querySelector('.mastery-suggestion').textContent = result.feedback.suggestion;
            } catch (error) {
                quantumResultDiv.querySelector('.mastery-comment').textContent = `评估失败: ${error.message}`;
            } finally {
                quantumLoader.style.display = 'none';
                quantumResultDiv.classList.remove('hidden');
            }
        }

        function setLoadingState(isLoading, elementToHide = topicFormContainer) {
            if (isLoading) {
                elementToHide.classList.add('hidden');
                loader.style.display = 'block';
            } else {
                loader.style.display = 'none';
            }
        }

        function showInitialState() {
            window.location.href = '/';
        }

        topicForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const newTopic = topicInput.value;
            if (newTopic) {
                mainContentContainer.classList.remove('hidden');
                summaryContainer.classList.add('hidden');
                getNextQuestion(newTopic, false);
            }
        });

        nextQuestionBtn.addEventListener('click', () => getNextQuestion(currentTopic, false));
        endSessionBtn.addEventListener('click', endSession);
        strengthenBtn.addEventListener('click', () => {
            summaryContainer.classList.add('hidden');
            mainContentContainer.classList.remove('hidden');
            getNextQuestion(currentTopic, true);
        });
        newLearningBtn.addEventListener('click', showInitialState);
        cancelLearningBtn.addEventListener('click', showInitialState);
    </script>
</body>
</html>